import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: [
      { id: 1, name: '手机', price: 1000, count: 1 },
      { id: 2, name: '电脑', price: 2000, count: 1 },
      { id: 3, name: '键盘', price: 200, count: 2 }
    ]
  },
  getters: {
    totalPrice(state) {
      return state.cart.reduce((sum, item) => sum + item.price * item.count, 0)
    }
  },
  mutations: {
    INCREMENT(state, id) {
      const item = state.cart.find(i => i.id === id)
      if (item) item.count++
    },
    DECREMENT(state, id) {
      const item = state.cart.find(i => i.id === id)
      if (item && item.count > 1) item.count--
    }
  },
  actions: {
  },
  modules: {
  }
})
